package com.sun.springbootelasticsearch.service;

import com.alibaba.fastjson.JSON;
import com.sun.springbootelasticsearch.bean.Content;
import com.sun.springbootelasticsearch.util.HtmlParse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ContentService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 爬取数据插入
     *
     * @param keyword
     * @return
     * @throws IOException
     */
    public boolean parseHtml(String keyword) throws IOException {
        List<Content> contentList = new HtmlParse().parseJD(keyword);
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2s");
        for (int i = 0; i < contentList.size(); i++) {
            bulkRequest.add(new IndexRequest("jd_goods").source(JSON.toJSONString(contentList.get(i)), XContentType.JSON));
        }
        BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        boolean b = responses.hasFailures();
        return !b;
    }


    /**
     * 搜索查询的数据
     *
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     */
    public List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException {
        if (pageNo <= 1) {
            pageNo = 1;
        }
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //精准查询
        TermQueryBuilder termQuery = QueryBuilders.termQuery("title", keyword);

        //分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);
        searchSourceBuilder.query(termQuery);

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title"); //标题高亮
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span'>");
        searchSourceBuilder.highlighter(highlightBuilder);

        //执行搜索
        searchRequest.source(searchSourceBuilder);
        //发送请求
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        List<Map<String, Object>> list = new ArrayList<>();
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {

            //解析高亮字段
            Map<String, HighlightField> fields = hit.getHighlightFields();
            HighlightField title = fields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();  //原来的数据

            if(title!=null){
                Text[] fragments = title.fragments(); //将高亮字段填充到原来的数据中
                String new_title = "";

                for (Text text : fragments) {
                    new_title += text;
                }
                sourceAsMap.put("title",new_title);  //替换原来的title
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}
